﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
//this script is for the  shell
public class SCT_Shell : MonoBehaviour
{
	public float lifeTime = 0.5f;
	public int shellDamage = 10;
	public ParticleSystem m_ExplosionParticles;         // Reference to the particles that will play on explosion.
	public ParticleSystem one;         // Reference to the particles that will play on explosion.
	public ParticleSystem two;         // Reference to the particles that will play on explosion.
	public ParticleSystem three;         // Reference to the particles that will play on explosion.
	public AudioSource m_ExplosionAudio;


	private void OnEnable()
	{
		// GetComponent<Renderer>().enabled = true;
		// 启动延迟激活碰撞器协程
		StartCoroutine(ActivateColliders());
	}


	void OnTriggerEnter(Collider col)
	{
		if (gameObject.name == "friendlyShell" && col.gameObject.tag == "Enemy")
		{
			// GetComponent<Rigidbody>().velocity = Vector3.zero;
			GetComponent<Collider>().enabled = false;
			// 延迟一点点时间等待声音播放，然后回收（可选）
			StartCoroutine(WaitAndReturn(0.5f));
		}
		else if (gameObject.name == "enemyShell" && col.gameObject.tag == "Player")
		{
			// GetComponent<Rigidbody>().velocity = Vector3.zero;
			GetComponent<Collider>().enabled = false;
			// 延迟一点点时间等待声音播放，然后回收（可选）
			StartCoroutine(WaitAndReturn(0.5f));
		}
	}

	private IEnumerator WaitAndReturn(float delay)
	{
		one.Stop(true, ParticleSystemStopBehavior.StopEmittingAndClear);
		two.Stop(true, ParticleSystemStopBehavior.StopEmittingAndClear);
		three.Stop(true, ParticleSystemStopBehavior.StopEmittingAndClear);

		m_ExplosionParticles.Play();
		yield return new WaitForSeconds(delay);
		if (gameObject.name != "SCT_Block2")
		{
			// 回收到对象池
			ShellPool.Instance.ReturnShell(this.gameObject);
		}
		else
		{
			gameObject.SetActive(false);
		}

	}

	private IEnumerator ActivateColliders()
	{
		GetComponent<BoxCollider>().enabled = true;
		yield return new WaitForSeconds(lifeTime);
		if (gameObject.name != "SCT_Block2")
		{
			// 回收到对象池
			ShellPool.Instance.ReturnShell(this.gameObject);
		}
		else
		{
			gameObject.SetActive(false);
		}
	}
}
